import React, { useState } from 'react';
import { Form, Input, message, Modal, Row } from 'antd';
import { GlobalFormLayout } from '@/layouts/Form';
import request from '@/utils/request';

const { Password } = Input;

function ModifyPasswordModal({ data = {}, visible, onCancel, form }) {
  const { userId, username } = data;
  const { getFieldDecorator, validateFields } = form;
  const [loading, setLoading] = useState(false);

  const handleSubmit = () => {
    validateFields((err, data) => {
      if (!err) {
        setLoading(true);
        request
          .post('/user/modifyPassword', { data })
          .then(() => {
            message.success('修改成功');
            onCancel();
          })
          .finally(() => setLoading(false));
      }
    });
  };

  return (
    <Modal
      title="修改密码"
      onOk={handleSubmit}
      okButtonProps={{ loading }}
      visible={visible}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form {...GlobalFormLayout}>
        <Form.Item>
          {getFieldDecorator('userId', {
            initialValue: userId,
          })(<Input hidden />)}
        </Form.Item>
        <Form.Item label="用户名">
          {getFieldDecorator('username', {
            initialValue: username,
          })(<Input readOnly placeholder="请输入" />)}
        </Form.Item>
        <Form.Item label="旧密码">
          {getFieldDecorator('oldPassword', {
            rules: [
              {
                required: true,
                message: '旧密码不能为空',
              },
            ],
          })(<Password placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item label="新密码">
          {getFieldDecorator('newPassword', {
            rules: [
              {
                required: true,
                message: '新密码不能为空',
              },
            ],
          })(<Password placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default Form.create()(ModifyPasswordModal);
